package com.bsoft.controller;

import com.bsoft.pojo.User;
import com.bsoft.repository.UserRAepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;
import java.util.Optional;

@RestController
public class MongoDBController {

    @Autowired
    private UserRAepository userRAepository;

    @PostMapping("/test")
    public String mongodb() {
        return "这个一个get请求";
    }

    @GetMapping("/save")
    public void save() {
        for (int i = 0; i < 1000; i++) {
            //创建对象
            User user = new User();
            user.setId(i);
            user.setUsername("hdh");
            user.setPassword("000000hdh");
            user.setCreateTime(new Date());
            User.Profile profile = new User.Profile();
            profile.setNickname("hdh");
            profile.setGender(1);
            user.setProfile(profile);
            //存储
            userRAepository.save(user);
        }

    }

    //根据id 查询
    @GetMapping("/selectById")
    public User findById() {
        Optional<User> user = userRAepository.findById(1);
        System.out.println(user);
        return user.get();
    }

    @GetMapping("/update")
    public void toUpdate() {
        Optional<User> user = userRAepository.findById(1);
        Assert.isTrue(user.isPresent(), "用户一定要存在");
        //更新
        User user1 = user.get();
        user1.setUsername("惠东海");
        userRAepository.save(user1);
    }

    @GetMapping("/delect")
    public void delect() {
        userRAepository.deleteById(1);

    }

    // 根据id查询一条记录
    @GetMapping("/selectByid")
    public void testSelectById() {
        Optional<User> user = userRAepository.findById(1);
        System.out.println(user.isPresent());
    }

    @GetMapping("/testSelectByIds")
    public void testSelctByIds() {
        Iterable<User> allById = userRAepository.findAllById(Arrays.asList(1, 4));
        allById.forEach(System.out::println);

    }
}
